import express from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import userRoutes from './routes/userRoutes';
import { swaggerSpec } from './config/swagger';
import swaggerUi from 'swagger-ui-express';
import wordRoutes from './routes/wordRoutes';
import categoryRoutes from './routes/categoryRoutes';
import audioRoutes from './routes/audioRoutes';
import studyPlanRoutes from './routes/studyPlanRoutes';
import studyGoalRoutes from './routes/studyGoalRoutes';
import studyRecordRoutes from './routes/studyRecordRoutes';
import listeningRoutes from './routes/listeningRoutes';
import listeningAnalysisRoutes from './routes/listeningAnalysisRoutes';
import morgan from 'morgan';
import helmet from 'helmet';

dotenv.config();

const app = express();

// 中间件
app.use(cors());
app.use(express.json());
app.use(morgan('dev'));
app.use(helmet());

// Swagger UI
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

// 路由
app.use('/api/users', userRoutes);
app.use('/api/words', wordRoutes);
app.use('/api/categories', categoryRoutes);
app.use('/api/audio', audioRoutes);
app.use('/api/study-plans', studyPlanRoutes);
app.use('/api/study-goals', studyGoalRoutes);
app.use('/api/study-records', studyRecordRoutes);
app.use('/api/listening', listeningRoutes);
app.use('/api/listening-analysis', listeningAnalysisRoutes);

// 测试路由
app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', message: 'Server is running' });
});

// 错误处理中间件
app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
  console.error(err.stack);
  res.status(500).json({
    status: 'error',
    message: 'Internal Server Error'
  });
});

// 数据库连接
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/admin')
  .then(() => console.log('Connected to MongoDB'))
  .catch((err: Error) => console.error('MongoDB connection error:', err));

// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
  console.log(`API Documentation available at http://localhost:${PORT}/api-docs`);
}); 